import { readFileSync } from "fs";
import { resolve } from "path";
import * as vscode from "vscode";
import { createDsLanguageClient, DsLanguageClient } from "./client";
import { languageClientNotifications } from "./util";
import { LanguageCommand } from "./common/types";

let extensionPath: string;
let client: DsLanguageClient;

class SchemaProvider implements vscode.TextDocumentContentProvider {
    onDidChange?: vscode.Event<vscode.Uri> | undefined;
    provideTextDocumentContent(uri: vscode.Uri): vscode.ProviderResult<string> {
        console.assert(uri.path[0] === "/", "A preceeding slash is expected on schema uri path.");
        const filePath = resolve(extensionPath, uri.path.substring(1));
        return readFileSync(filePath).toString();
    }
}

export async function activate(context: vscode.ExtensionContext) {
    extensionPath = context.extensionPath;
    context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider("idsc-schema", new SchemaProvider()));

    client = createDsLanguageClient(context);

    context.subscriptions.push(vscode.commands.registerCommand(LanguageCommand.selectFileBranchCommand, client.showFileBranches));
    context.subscriptions.push(vscode.commands.registerCommand(LanguageCommand.selectProgramMetadata, client.selectMetadataFile));
    context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(listener => {
        if (listener) {
            client.refreshLanguageStatus(listener.document.uri);
        }
    }));
    context.subscriptions.push(vscode.workspace.onDidChangeWorkspaceFolders(client.workspaceFoldersChanged));
    context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(listener => {
        if (listener.affectsConfiguration("ds")) {
            client.sendNotification(languageClientNotifications["dsclient/configurationChanged"], client.configurations.getWindowConfiguration());
        }
    }));

    await client.start();

    let folders = vscode.workspace.workspaceFolders;
    if (folders) {
        for (const folder of folders) {
            client.configurations.addWorkspace(folder.uri.fsPath);
        }
    }

    let config = client.configurations.getWindowConfiguration();
    client.sendNotification(languageClientNotifications["dsclient/initializeServerWindowConfigurations"], config);
    if (vscode.window.activeTextEditor) {
        client.refreshLanguageStatus(vscode.window.activeTextEditor.document.uri);
    }

}

export function deactivate(): Thenable<void> | undefined {
    if (!client) {
        return undefined;
    }
    return client.stop();
}
